var express = require('express');
var router = express.Router();
var userModel = require('../db/user')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/users', async (req,res) => {
  // const {_id} = req.body
  const data = await userModel.find()
  res.send({
    code: 200,
    data
  })
})


router.put('/updateUsers', async (req, res) => {
  const { deparTment, posiTion, phone, postBox, EmployeeRoles,entryTime,SuperiorAuthority,initialPassword,_id } = req.body;
  if (!_id) {
    return res.send({ code: 400, msg: "缺少用户ID" });
  }
  // 构建要更新的字段对象
  const updateFields = {};
  if (deparTment !== undefined) updateFields.deparTment = deparTment;
  if (posiTion !== undefined) updateFields.posiTion = posiTion;
  if (phone !== undefined) updateFields.phone = phone;
  if (postBox !== undefined) updateFields.postBox = postBox;
  if (EmployeeRoles !== undefined) updateFields.EmployeeRoles = EmployeeRoles;
  if (entryTime !== undefined) updateFields.entryTime = entryTime;
  if (SuperiorAuthority !== undefined) updateFields.SuperiorAuthority = SuperiorAuthority;
  if (initialPassword !== undefined) updateFields.initialPassword = initialPassword;

  if (Object.keys(updateFields).length === 0) {
    return res.send({ code: 400, msg: "没有需要更新的字段" });
  }

  try {
    const data = await userModel.updateOne({ _id }, { $set: updateFields });
    res.send({
      code: 200,
      data
    });
  } catch (err) {
    res.send({ code: 500, msg: "服务器错误" });
  }
});
module.exports = router;
